<template>
  <div class="login-container">

    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" auto-complete="on" label-position="left">

      <div class="title-container">
        <h3 class="title">壹馨诊所管理平台</h3>
      </div>

      <el-form-item prop="username">
        <span class="svg-container">
          <svg-icon icon-class="user" />
        </span>
        <el-input
          ref="username"
          v-model="loginForm.phone"
          placeholder="手机号"
          name="username"
          type="text"
          tabindex="1"
          auto-complete="on"
          @blur="changePhone"
          @input="inputPhone"
        />
      </el-form-item>

      <el-form-item prop="password">
        <span class="svg-container">
          <svg-icon icon-class="password" />
        </span>
        <el-input
          :key="passwordType"
          ref="password"
          v-model="loginForm.password"
          :type="passwordType"
          placeholder="密码"
          name="password"
          tabindex="2"
          auto-complete="on"
          @keyup.enter.native="handleLogin"
        />
        <span class="show-pwd" @click="showPwd">
          <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
        </span>
      </el-form-item>
      <el-row :gutter=10>
        <el-col :span=12 >
          <el-form-item prop="dept">
            <el-select  
              v-model="loginForm.deptId" 
              placeholder="选择登录部门" 
              style="background-color: white;border: 1px solid gray;width: 100%;"
              :loading="deptLoading"
            >
              <el-option
                v-for="item in depts"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
                @click.native="selectLoginDept(item)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=12 >
          <el-form-item prop="jobDuty">
            <el-select  v-model="loginForm.jobDuty" placeholder="选择职务" style="background-color: white;border: 1px solid gray;width: 100%;" >
              <el-option
                v-for="item in jobDutyEnum"
                :key="item.jobDutyId"
                :label="item.jobDutyName"
                :value="item.jobDutyId"
                @click.native="selectJobDuty(item)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter=10>
      </el-row>
      <el-row :gutter="10" v-if="isDoctor">
        <el-col :span=24 >
          <el-form-item prop="isVisit">
            <el-select  v-model="loginForm.isVisit" placeholder="是否出诊" style="background-color: white;border: 1px solid gray;;width: 100%;">
              <el-option
                v-for="item in visitEnum"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                @click.native="selectVisit(item)"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="isVisit">
        <el-col :span=12 >
          <el-form-item prop="workAddress">
            <el-select  v-model="loginForm.workAddress" placeholder="选择诊室" style="background-color: white;border: 1px solid gray;width: 100%;" :disabled="workAddressIsDisabled">
              <el-option
                v-for="item in workAddresses"
                :key="item.id"
                :label="item.name"
                :value="item.id"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span=12 >
          <el-form-item prop="jobOffice">
            <el-select  v-model="loginForm.jobOffice" placeholder="选择科室" style="background-color: white;border: 1px solid gray;;width: 100%;">
              <el-option
                v-for="item in jobOffices"
                :key="item.jobOfficeId"
                :label="item.jobOfficeName"
                :value="item.jobOfficeId"
                >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span=24 >
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;height: 50px;" @click.native.prevent="handleLogin">登录</el-button>
        </el-col>
      </el-row>
      <el-button type="text" @click="toRegister">注册账号</el-button>

    </el-form>
    <el-dialog title="注册" :visible.sync="userInfoVisible" :closeOnClickModal="false">
      <h2>基本信息</h2>
      <el-form ref="userInfo" :model="userInfo" label-width="80px" :rules="registerRules" >
        <el-form-item :label="(index+1)+'级审批'" v-for="(jobDuty, index) in this.auditPreset" :key="jobDuty.id" prop="auditPreset">
          <span>{{ jobDuty.name }}</span>
          <el-select v-model="jobDuty.auditUser" placeholder="请选择" style="width: 100%">
            <el-option
              v-for="item in jobDuty.auditAvailableUserList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="姓名" prop="name">
            <el-input v-model="userInfo.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="userInfo.password" />
        </el-form-item>
        <el-form-item label="确认密码" prop="password">
            <el-input type="password" v-model="userInfo.password2" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
            <el-input  v-model="userInfo.phone" maxlength="11"/>
        </el-form-item>
        <el-form-item label="身份证号" prop="idCard">
            <el-input v-model="userInfo.idCard" maxlength="18"/>
        </el-form-item>
        <el-row :gutter="10">
          <el-col :span=8>
            <el-form-item label="学历" prop="education">
              <el-select style="width:100%" v-model="userInfo.education" placeholder="请选择">
                <el-option
                  v-for="item in educationEnum"
                  :key="item"
                  :label="item"
                  :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="社会职业">
              <el-select style="width:100%" v-model="userInfo.job" placeholder="请选择">
                <el-option
                  v-for="item in jobs"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                  @click.native="selectJob(item.id)"
                  >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span=8 >
            <el-form-item label="社会职称">
              <el-select style="width:100%" v-model="userInfo.jobTitle" placeholder="请选择" :disabled="jobTitleIsDisabled">
                <el-option
                  v-for="item in jobTitles"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirm">确 定</el-button>
          <div style="width:200px;display: inline-block;"> </div>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { setToken } from '@/utils/auth'
import { setDeptCookie, setWorkAddressCookie, setJobOfficeCookie } from '@/utils/cookiesUtil'
import { register, login } from '@/api/user'
import { getList as getJobList } from '@/api/job'
import { getListByJobId } from '@/api/jobTitle'
import { getListByDeptId as getWorkAddressListByDeptId } from '@/api/workAddress'
import { getList as getDeptList, getDeptListByphone } from '@/api/dept'
import { getList as getJobTypeList } from '@/api/jobType'
import { getInfo as getAuditInfo } from '@/api/auditFlow'

export default {
  name: 'Login',
  data() {
    // login rules
    const validateUsername = (rule, value, callback) => {
      if (value && value.length != 11) {
        callback(new Error('请输入正确的手机号'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if(value && (value.length < 6 || value.length > 20)) {
        callback(new Error('密码长度必须在 6 - 20 之间'))
      } else {
        callback()
      }
    }
    // register rules
    const validateName = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入姓名'))
      } else {
        callback()
      }
    }
    const validateRegisterPassword = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入密码'))
      } else if(value.length < 6 || value.length > 20) {
        callback(new Error('密码长度必须在 6 - 20 之间'))
      } else if(this.userInfo.password && this.userInfo.password2 && this.userInfo.password != this.userInfo.password2) {
        callback(new Error('两次输入得密码不同'))
      } else {
        callback()
      }
    }
    const validatePhone = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入电话号码'))
      } else if(value.length != 11) {
        callback(new Error('请输入11位电话号码'))
      }  else {
        callback()
      }
    }
    const validateIdCard = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请输入身份证号'))
      } else if(value.length != 18) {
        callback(new Error('请输入18位身份证号码'))
      }  else {
        callback()
      }
    }
    const validateDept = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择部门'))
      } else {
        callback()
      }
    }
    const validateWorkAddress = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择诊室'))
      } else {
        callback()
      }
    }
    const validateJobOffice = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择科室'))
      } else {
        callback()
      }
    }
    const validateJobDuty = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择职务'))
      } else {
        callback()
      }
    }
    const validateAuditPreset = (rule, value, callback) => {
      for (let index = 0; index < this.auditPreset.length; index++) {
        if(!this.auditPreset[index].auditUser) callback(new Error('请选择审批人'))
      }
      callback()
    }
    const validateIsVisit = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择是否出诊'))
      } else {
        callback()
      }
    }
    const validateEducation = (rule, value, callback) => {
      if (!value) {
        callback(new Error('请选择学历'))
      } else {
        callback()
      }
    }
    
    return {
      loginForm: {
        
      },
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        jobDuty: [{ required: true, trigger: 'blur', validator: validateJobDuty }],
        isVisit: [{ required: true, trigger: 'blur', validator: validateIsVisit }],
        workAddress: [{ required: true, trigger: 'blur', validator: validateWorkAddress }],
        jobOffice: [{ required: true, trigger: 'blur', validator: validateJobOffice }],
      },
      registerRules: {
        name: [{ required: true, trigger: 'blur', validator: validateName }],
        password: [{ required: true, trigger: 'blur', validator: validateRegisterPassword }],
        phone: [{ required: true, trigger: 'blur', validator: validatePhone }],
        idCard: [{ required: true, trigger: 'blur', validator: validateIdCard }],
        dept: [{ required: true, trigger: 'blur', validator: validateDept }],
        jobDuty: [{ required: true, trigger: 'blur', validator: validateJobDuty }],
        workAddress: [{ required: true, trigger: 'blur', validator: validateWorkAddress }],
        auditPreset: [{ required: true, trigger: 'blur', validator: validateAuditPreset }],
        education: [{ required: true, trigger: 'blur', validator: validateEducation }],
        
      },
      loading: false,
      passwordType: 'password',
      redirect: undefined,
      userInfoVisible: false,
      userInfo:{},
      educationEnum: ["专科", "本科", "研究生", "博士"],
      jobs : [],
      jobTitles: [],
      jobTypes:[],
      jobOffices: [],
      depts: [],
      workAddresses: [],
      jobDutys: [],
      jobTitleIsDisabled: true,
      jobDutyIsDisabled: true,
      workAddressIsDisabled: true,
      loginDept: undefined,
      loginWorkaddress: undefined,
      loginOffice: undefined,
      auditPreset: [],
      jobDutyEnum: [],
      jobDutyAllEnum: [],
      isDoctor: false,
      visitEnum: [{id:1, name: '出诊'}, {id:0, name: '不出诊'}],
      isVisit: false,
      deptLoading: false,
    }
  },
  watch: {
    $route: {
      handler: function(route) {
        this.redirect = route.query && route.query.redirect
      },
      immediate: true
    }
  },
  created() {

  },
  methods: {
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true
          console.log('this.loginForm',this.loginForm)
          login(this.loginForm).then((res) => {
            console.log(res.data)
            setToken(res.data.token)
            // setDeptCookie(JSON.parse(JSON.stringify(this.loginForm.dept)))
            setDeptCookie(JSON.stringify(this.loginForm.dept))
            setWorkAddressCookie(this.loginForm.workAddress)
            setJobOfficeCookie(this.loginForm.jobOffice)
            console.log('---login---')
            this.$router.push({ path: '/myCenter/message' })
            this.loading = false
          }).catch((err) => {
            console.log(err)
            this.loading = false
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    toRegister() {
      getDeptList().then(deptRes=>{
        this.depts = deptRes.data
      })
      getJobList().then(jobRes=>{
        this.jobs = jobRes.data
      })
      getJobTypeList().then(jobTypeRes=>{
        this.jobTypes = jobTypeRes.data
      })
      getAuditInfo({businessCode: 'register'}).then(res=> {
        this.auditPreset = res.data
      })
      this.userInfoVisible = true
    },
    confirm() {
      this.$refs.userInfo.validate(valid => {
        if (valid) {
          this.$set(this.userInfo, 'jobDuty', [this.userInfo.jobDuty])
          console.log(this.userInfo)
          this.userInfo.auditUserIds = this.auditPreset.map(jobDutyVo => Number(jobDutyVo.auditUser))
          register(this.userInfo).then(registerRes=>{
            console.log(registerRes);
            this.$message({
              message: '注册成功，等待审批',
              type: 'success'
            })
            this.userInfoVisible = false
            this.userInfo = {}
          }).catch(err=>{
            console.log(err)
          })
          
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    cancel() {
      this.userInfoVisible = false
    },
    selectJob(jobId) {
      this.jobTitleIsDisabled = true
      this.$set(this.userInfo, 'jobTitle', '')
      getListByJobId({'jobId': jobId}).then(jobTitleRes=> {
        console.log("job title list", jobTitleRes)
        this.jobTitles = jobTitleRes.data
        this.jobTitleIsDisabled = false
      })
    },
    selectLoginDept(dept) {
      console.log(dept)
      this.workAddressIsDisabled = true
      this.$set(this.loginForm, 'jobDuty', undefined)
      this.$set(this.loginForm, 'isVisit', undefined)
      this.$set(this.loginForm, 'jobOffice', undefined)
      this.$set(this.loginForm, 'workAddress', undefined)
      this.loginForm.dept = dept
      getWorkAddressListByDeptId({'deptId' : dept.deptId}).then(workAddressRes=> {
        console.log('workAddress: ', workAddressRes.data)
        this.workAddresses = workAddressRes.data
        this.workAddressIsDisabled = false
      })
      this.jobDutyEnum = this.jobDutyAllEnum.filter(jobDuty => jobDuty.deptId === dept.deptId)
    },
    inputPhone() {
      this.depts = []
      this.jobOffices = []
      this.jobDutyAllEnum = []
      this.$set(this.loginForm, 'deptId', undefined)
      this.$set(this.loginForm, 'jobDuty', undefined)
      this.$set(this.loginForm, 'workAddress', undefined)
      this.$set(this.loginForm, 'jobOffice', undefined)
    },
    changePhone() {
      console.log(this.loginForm.phone)
      if(this.loginForm.phone.length == 11) {
        this.deptLoading = true
        getDeptListByphone(this.loginForm.phone).then(res=> {
          console.log(res)
          this.depts = res.data.userDeptList
          this.jobOffices = res.data.userJobOfficeList
          this.jobDutyAllEnum = res.data.userJobDutyList
          this.deptLoading = false
        }).catch((err) => {
          console.log(err)
          this.deptLoading = false
          this.$message({
            type: 'info',
            message: '已取消'
          });          
        })
      }
    },
    remoteMethod() {

    },
    selectJobDuty(jobDuty) {
      this.$set(this.loginForm, 'isVisit', undefined)
      this.$set(this.loginForm, 'jobOffice', undefined)
      this.$set(this.loginForm, 'workAddress', undefined)
      if(jobDuty.jobDutyName.includes("医生")) {
        this.isDoctor = true
        this.isVisit = true
        this.$set(this.loginForm, 'isVisit', 1) // 默认出诊
      } else {
         this.isDoctor = false
         this.isVisit = false
         this.$set(this.loginForm, 'isVisit', 0)
      }
    },
    selectVisit(item) {
      this.$set(this.loginForm, 'jobOffice', undefined)
      this.$set(this.loginForm, 'workAddress', undefined)
      if(item.id === 1) {
        this.isVisit = true
      } else {
         this.isVisit = false
      }
    },
  }
}
</script>

<style lang="scss">
/* 修复input 背景不协调 和光标变色 */
/* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

// $bg:#283443;
// $light_gray:#fff;
// $cursor: #fff;

$bg:white;
$light_gray:#283443;
$cursor: #283443;

@supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
  .login-container .el-input input {
    color: $cursor;
  }
}

/* reset element-ui css */
.login-container {
  .el-input {
    display: inline-block;
    height: 47px;
    width: 85%;

    input {
      background: transparent;
      border: 1px solid #DCDFE6;
      -webkit-appearance: none;
      border-radius: 0px;
      padding: 12px 5px 12px 15px;
      height: 47px;

      &:-webkit-autofill {
        box-shadow: 0 0 0px 1000px $bg inset !important;
        -webkit-text-fill-color: $cursor !important;
      }
    }
  }

  .login-form {
    .el-form-item {
    border: 1px solid rgba(255, 255, 255, 0.1);
    background-color: rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    color: #454545;
    input {
      border: 1px;
    }
  }
  }
  
}
</style>

<style lang="scss" scoped>
// $bg:#2d3a4b;
// $dark_gray:#889aa4;
// $light_gray:#eee;

$bg:white;
$dark_gray:#2d3a4b;
$light_gray:#2d3a4b;



.login-container {
  min-height: 100%;
  width: 100%;
  background-color: $bg;
  overflow: hidden;

  .login-form {
    position: relative;
    width: 520px;
    max-width: 100%;
    padding: 160px 35px 0;
    margin: 0 auto;
    overflow: hidden;
  }

  .svg-container {
    padding: 6px 5px 6px 15px;
    vertical-align: middle;
    width: 30px;
    display: inline-block;
  }

  .title-container {
    position: relative;

    .title {
      font-size: 26px;
      color: $light_gray;
      margin: 0px auto 40px auto;
      text-align: center;
      font-weight: bold;
    }
  }

  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: $dark_gray;
    cursor: pointer;
    user-select: none;
  }
}
</style>
